package cn.itcast.gateway.filters;

import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        判断请求参数中是否带有token。如果没有返回403状态码
//        request.getParameter("token")

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

//        获取token参数
        String token = request.getQueryParams().getFirst("token");

//        判断token是否有值
        if (StringUtils.isNotBlank(token)) {
//            token不为空，直接进入到后面的微服中
            return chain.filter(exchange); //直接放行
        }else{
//            token为空   如果没有返回403状态码
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete(); //直接返回给浏览器
        }
    }

    @Override
    public int getOrder() {  //这个值越小 当前过滤器越优先执行，一般不用指定
        return 0;
    }
}
